package com.ku.consumerpay.service.mq;

import com.ku.constants.OrderStatus;
import com.ku.consumerpay.mapper.CustomerAccountMapper;
import com.ku.service.OrderService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: rocketMQKill
 * @description: RocketMQ事务消息的事务监听器
 * @author: JokerKu
 * @create: 2020-05-06 21:07
 **/

@Component
public class TransactionListenerImpl implements TransactionListener {

    @Autowired
    private CustomerAccountMapper customerAccountMapper;


    //执行本地事务
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object arg) {
        Map<String, Object> params = (HashMap<String, Object>) arg;
        //获取PayServiceImpl封装的params
        String userId = (String) params.get("userId");
        String orderId = (String) params.get("orderId");
        String accountId = (String) params.get("accountId");
        BigDecimal money = (BigDecimal) params.get("money");//money表示当前的支付款
        BigDecimal newBalance = (BigDecimal) params.get("newBalance");//newBalance是扣减完账户的余额
        Integer currentVersion = (Integer) params.get("currentVersion");
        try {
            //扣减用户账户的钱
            int updateResult = customerAccountMapper.updateBalance(accountId, newBalance, currentVersion, new Date());
                //用户账户扣减成功
            if (updateResult == 1) {
                //让platformPay可见这条消息
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }

        return LocalTransactionState.ROLLBACK_MESSAGE;
    }

    //执行回调检查
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        return null;
    }
}
